<template>
  <a-form-model
    ref="ruleForm"
    :model="newModelData"
    :rules="rules"
    layout="horizontal"
    class="AsteriskAfter newEditStyle rightDrawerWithoutCol"
  >
    <a-row :gutter="36">
      <a-col :md="12" :sm="24" v-if="newModelData.type == 1">
        <a-form-model-item label="文件路径" prop="component">
          <a-input v-model="newModelData.component"/>
        </a-form-model-item>
      </a-col>
      <a-col :md="12" :sm="24"  v-if="newModelData.type == 1">
          <a-form-model-item label="图标" prop="icon">
            <a-input v-model="newModelData.icon"/>
          </a-form-model-item>
      </a-col>
      <a-col :md="12" :sm="24" v-if="newModelData.type == 1">
        <a-form-model-item label="路由路径" prop="path">
          <a-input v-model="newModelData.path"/>
        </a-form-model-item>
      </a-col>
      <a-col :span="24" :sm="24" v-if="newModelData.type == 2">
        <a-form-model-item label="API权限" prop="permissionUri" style="height: auto">
          <a-textarea v-model="newModelData.permissionUri" :rows="3"/>
        </a-form-model-item>
      </a-col>
      <a-col :md="12" :xs="24">
        <a-form-model-item label="备注" prop="remark">
          <a-input v-model="newModelData.remark"/>
        </a-form-model-item>
      </a-col>
      <a-col :md="12" :xs="24" v-if="newModelData.type == 1">
        <a-form-model-item label="路由名称" prop="router">
          <a-input v-model="newModelData.router"/>
        </a-form-model-item>
      </a-col>
      <a-col :md="12" :xs="24">
        <a-form-model-item label="排序" prop="sortNo">
          <a-input-number v-model="newModelData.sortNo" :min="0" style="width: 100%"/>
        </a-form-model-item>
      </a-col>
      <a-col :md="12" :xs="24">
        <a-form-model-item label="名称" prop="title">
          <a-input v-model="newModelData.title"/>
        </a-form-model-item>
      </a-col>
      <a-col :md="12" :xs="24">
        <a-form-model-item label="选择父菜单" prop="parentIds" >
          <a-cascader :placeholder="$t('pleaseSelect')" :options="menuList" :fieldNames="{label:'title',value:'id',children: 'childMenus'}" allowClear  v-model="newModelData.parentIds" change-on-select @change="onChange" />
        </a-form-model-item>
      </a-col>
      <a-col :md="12" :xs="24">
        <a-form-model-item label="权限码" prop="code">
          <a-input v-model="newModelData.code"/>
        </a-form-model-item>
      </a-col>
      <a-col :md="12" :xs="24">
        <a-form-model-item label="是否展示" prop="display">
          <a-radio-group style="padding-bottom: 24px" name="display" v-model="newModelData.display">
            <a-radio :value="1">
              是
            </a-radio>
            <a-radio :value="0">
              否
            </a-radio>
          </a-radio-group>
        </a-form-model-item>
      </a-col>
      <a-col :md="12" :xs="24">
        <a-form-model-item label="类型" prop="type">
          <a-radio-group style="padding-bottom: 24px" :disabled="!!recordData.id" name="type" v-model="newModelData.type">
            <a-radio :value="1">
              菜单
            </a-radio>
            <a-radio :value="2">
              按钮
            </a-radio>
          </a-radio-group>
        </a-form-model-item>
      </a-col>
    </a-row>
  </a-form-model>
</template>
<script>
import { mapState } from 'vuex'
import menuApi from '@/api/modules/system/menu'

export default {
  name: 'NewEditMenu',
  props: {
    recordData: {
      type: Object,
      default: () => {
        return {}
      }
    },
  },
  computed: {
    ...mapState({
    })
  },
  data () {
    return {
      newModelData: {
        component: '',
        icon: '',
        path: '',
        permissionUri: '',
        remark: '',
        router: '',
        sortNo: '',
        title: '',
        code: '',
        display: 1,
        type: 1,
        parentIds: [],
      },
      rules: {
        component:[{ required: true, message: this.$t('pleaseInput'), trigger: ['change', 'blur']}],
        icon:[{ required: true, message: this.$t('pleaseInput'), trigger: ['change', 'blur']}],
        path:[{ required: true, message: this.$t('pleaseInput'), trigger: ['change', 'blur']}],
        // permissionUri:[{ required: true, message: this.$t('pleaseInput'), trigger: ['change', 'blur']}],
        remark:[{ required: true, message: this.$t('pleaseInput'), trigger: ['change', 'blur']}],
        router:[{ required: true, message: this.$t('pleaseInput'), trigger: ['change', 'blur']}],
        sortNo:[
          { required: true,
            validator: (rule, value, callback) => {
              if (!/^[0-9]+$/.test(value)) {
                callback(new Error(this.$t('onlyInputNumber')))
                return
              }
              callback()
            },
            trigger: ['change']
          }
          ],
        parentIds:[
          {
            required: true,
            trigger: ['change'],
            validator: (rule, value, callback) => {
              if (!this.newModelData.parentIds?.length) {
                callback(new Error(this.$t('pleaseSelect')))
                return
              }
              callback()
            }
            },
          ],
        title:[{ required: true, message: this.$t('pleaseInput'), trigger: ['change', 'blur']}],
        // code:[{ required: true, message: this.$t('pleaseInput'), trigger: ['change', 'blur']}],
        // parentIds:[{ required: true, message: this.$t('pleaseSelect'), trigger: ['change', 'blur']}],
      },
      menuList: [],
      disabledArr: []
    }
  },
  mounted() {
    this.initForm()
  },
  methods: {
    onChange(e){
      console.log(e)
    },
    // 初始化表单
    initForm () {
      const vm = this
      vm.$refs.ruleForm && vm.$refs.ruleForm.resetFields()
      vm.$refs.ruleForm && vm.$refs.ruleForm.clearValidate()
      this.deleteBtnOption(vm.recordData.menuList)
      this.deleteProperty(vm.recordData.menuList)
      this.toI18n(vm.recordData.menuList)
      this.menuList = [{
        id: 'allMenusId',
        remark: '',
        sortNo: 1,
        title: '所有菜单',// all menus
        type: 1,
        childMenus: vm.recordData.menuList
      }]
      if (vm.recordData.id) {
        // 编辑、新增子菜单、新增按钮
        Object.keys(this.newModelData).forEach(e => {
          if (e === 'parentIds') {
            // 父级递归出来的数组  需加上所有菜单 并反转数组内的元素（递归出来的值是从内至外）
            let arr = vm.recordData[e]
            arr.push('allMenusId')
            arr.reverse()
            this.newModelData[e] = arr
          } else if (vm.recordData.chooseType == 'edit') {
            //编辑
            if (e === 'display') {
              // type为Boolean类型  需转为数字类型
              this.newModelData[e] = Number(vm.recordData[e])
            } else {
              this.newModelData[e] = vm.recordData[e]
            }
          }
        })
        if (vm.recordData.chooseType == 'edit') {
          //编辑
          this.disabledArr.push(vm.recordData.id)
          this.setDisabled(this.menuList)
        } else if (vm.recordData.chooseType == 'newSubBtn') {
          this.newModelData.type = 2
          this.newModelData.display = 0
        }
        //非编辑情况均为新增  需删除id
        if (vm.recordData.chooseType != 'edit') {
          delete this.newModelData.id
          delete this.recordData.id
        }
      }
    },
    //清除子菜单数组长度为0的字段
    deleteProperty (arr) {
      arr.forEach(a => {
        if (a.childMenus && a.childMenus.length !== 0) {
          //长度不为0，继续往下执行
          this.deleteProperty(a.childMenus)
        } else {
          //长度为0，删除该字段
          delete a.childMenus
        }
      })
    },
    // 编辑时禁用当前节点及当前节点的子节点
    setDisabled (arr) {
      arr.map(a => {
        if (this.disabledArr.includes(a.id) || this.disabledArr.includes(a.parentId)) {
          a.disabled = true
          this.disabledArr.push(a.id)
        }
        if (a.childMenus) {
          this.setDisabled(a.childMenus, this.disabledArr)
        }
      })
    },
    getFormData() {
      const vm = this
      return new Promise((resolve, reject) => {
        this.$refs.ruleForm.validate(valid => {
          if (!valid) {
            reject(valid)
            return
          }
          // this.recordData.parentId
          // newModelData 新数据放后面  用于覆盖原有数据
          let data = { ...vm.recordData,  ...vm.newModelData }
          let tempParentId = data.parentIds[data.parentIds.length - 1]
          data.parentId = tempParentId == 'allMenusId' ? undefined : tempParentId
          //移除非需要数据，减小请求数据大小
          delete data.menuList
          delete data.childMenus
          delete data.chooseType
          delete data.parentIds
          if (data.type === 2) {
            delete data.component
            delete data.icon
            delete data.path
            delete data.router
          }
          resolve(data)
        })
      })
    },
    // 移除按钮选项
    deleteBtnOption (arr) {
      let i = arr.length
      while (i--) {
        let item = arr[i]
        if (item.type == 2) {
          arr.splice(i, 1)
        } else if (item.childMenus && item.childMenus.length !== 0) {
          this.deleteBtnOption(item.childMenus)
        }
      }
    },
    //清除子菜单数组长度为0的字段
    toI18n (arr) {
      arr.forEach(a => {
        if (a.title) {
          a.title = this.$t(a.title)
        }
        if (a.childMenus && a.childMenus.length !== 0) {
          //长度不为0，继续往下执行
          this.toI18n(a.childMenus)
        }
      })
    },
    getDetail(){
      menuApi.info({ id: this.recordData.id }).then(res => {
        let keys = Object.keys(this.newModelData)
        Object.keys(res.data).forEach(e => {
          if (keys.includes(e)) {
            this.newModelData[e] = res.data[e] || typeof res.data[e] === 'number' ? 0 : ''
          }
        })
      })
    }
  },
  watch: {
  }
}
</script>

<style lang="less" scoped>
  .newBtnWithPlus{
  }
  .ant-form-item {
    height: 70px;
    margin-bottom: 0;
  }
</style>
